import axios from 'axios';
import MD5 from 'md5';
import moment from 'moment';
import { Message, Loading } from 'element-ui';
import _ from 'lodash';

import Mock from 'mockjs';
// if (process.env.MOCK) {
//   require('./mock.js')
// }

// const { config } = require('@/../config/axios_config.js');
import { mergeConfig } from '@/mergeConfig.js';
let serverConfig = null;
if (_.has(window, 'server_config')) {
  serverConfig = window.server_config.getServerConfig();
}

const CONFIG = mergeConfig(serverConfig);

// import config from './config.js';
// require/import 目前看来两者皆可

axios.defaults.timeout = 1000 * 30;
axios.defaults.baseURL = `${CONFIG.host}`;
axios.defaults.headers.post['Content-Type'] =
  'Content-Type:application/x-www-form-urlencoded; charset=UTF-8'; //预防跨域
// 如果使用全局loading
// let loading;
// function openLoading() {loading = Loading.service({lock: true,background: 'rgba(255,255,255,0.6)'});}
// function closeLoading() {loading.close()}
// 不过实际业务不怎么待见全局loading（无论它们知道与否）

// 添加请求拦截器
axios.interceptors.request.use(
  config => {
    console.log(
      '%c [ config ]-37',
      'font-size:13px; background:pink; color:#bf2c9f;',
      config,
    );
    if (config.method == 'post' && !_.has(config, 'params.verifykey')) {
      let verifykey = MD5(moment().format('YYYYMMDD')).toUpperCase();
      _.set(config, 'params.verifykey', verifykey);
    }
    // 在发送请求之前做些什么
    // 如果使用全局loading，可以在这里open，不过……
    return config;
  },
  error => {
    // 对请求错误做些什么
    return Promise.reject(error);
  },
);

// 添加响应拦截器
axios.interceptors.response.use(
  function(response) {
    // 如果使用全局loading，可以在这里close，不过……
    // 对响应数据做点什么
    if (response.status === 200) {
      return response.data; //对明确的200做脱壳处理
    }
    // http://www.axios-js.com/zh-cn/docs/#%E5%93%8D%E5%BA%94%E7%BB%93%E6%9E%84 官网的响应结构
    return response;
  },
  function(error) {
    // 对响应错误做点什么
    if (error && error.response) {
      switch (error.response.status) {
        case 400:
          error.message = '请求错误(400)';
          break;
        case 401:
          this.$router.push('/login');
          break;
        case 403:
          error.message = '拒绝访问(403)';
          break;
        case 404:
          error.message = '请求出错(404)';
          break;
        case 408:
          error.message = '请求超时(408)';
          break;
        case 500:
          error.message = '服务器错误(500)';
          break;
        case 501:
          error.message = '服务未实现(501)';
          break;
        case 502:
          error.message = '网络错误(502)';
          break;
        case 503:
          error.message = '服务不可用(503)';
          break;
        case 504:
          error.message = '网络超时(504)';
          break;
        case 505:
          error.message = 'HTTP版本不受支持(505)';
          break;
        default:
          error.message = `连接出错(${error.response.status})!`;
      }
    } else {
      error.message = '连接服务器失败!';
    }
    return Promise.reject(error);
  },
);

let api = {
  testGet: function(data) {
    data = data || { a: 1, b: 2 };
    return axios.get('/testGet', {
      params: data,
    });
  },
  testPost: function(data) {
    data = data || { a: 1, b: 2 };
    return axios.post('/testPost', {
      data: data,
    });
  },
  testMirrorForce: function(params, data) {
    data = data || { a: 1, b: 2 };
    return axios.post(`/test/MirrorForce`, data, {
      params: params,
    });
  },
  getQiniuToken: function() {
    // http://test.zfxfu.com:60967/api/Material/GetQiNiuToken
    const url = `http://ewapi.chenxi18.com:82/api/Material/GetQiNiuToken`;
    return axios.get(url);
  }, //获取七牛Token,不在actions中再封装

  //后面跟正式的api接口
  getCompanyEmployee: function(params, data) {
    const url = `${CONFIG.hostCE}/api/Company/GetCompanyEmployee`;
    return axios.post(url, data, {
      params: params,
    });
  }, //获取员工信息

  getResourceChannels: function(params, data) {
    // /mock资源渠道
    return axios.post('/api/Company/GetFromSourceList', data, {
      params: params,
    });
  }, //获取渠道

  getEsCompanyList: function(params, data) {
    // /mock工作台
    return axios.post('/api/Company/GetEsCompanyList', data, {
      params: params,
    });
  }, //获取企业微信信息
  getCrmProduct: function(params, data) {
    // /mock工作台
    return axios.post('/api/Company/GetCrmProduct', data, {
      params: params,
    });
  }, //获取分公司产品信息
  getPayType: function(params, data) {
    // /mock工作台
    return axios.post('/api/Company/GetPayType', data, {
      params: params,
    });
  }, //取得支付方式

  getCompanyDepartmentList: function(params, data) {
    // return axios.post('/api/Company/GetCompanyDepartmentList', data, {
    return axios.post('/api/Company/GetAllCompanyDepartmentList', data, {
      params: params,
    });
  }, //高层获取部门列表

  getCompanyEmployeeList: function(params, data, version) {
    // /mock销售
    let url;
    if (version == 1) url = '/api/Company/GetCompanyEmployeeList'; //原接口
    if (version == 2)
      url = '/api/Company/GetExternalContactsCompanyEmployeeList'; //2023-10-16改接口
    return axios.post(url, data, {
      params: params,
    });
  }, //组长获取部门成员

  员工userid下发: function(params, data) {
    // /mock销售
    let url = '/api/SCRM/GeteScrmCrmUser';
    return axios.post(url, data, {
      params: params,
    });
  }, //员工userid下发

  getScrmFollowUserList: function(params, data) {
    // return axios.post('/mock表格', data, {
    return axios.post('/api/SCRM/GetScrmFollowUserList', data, {
      params: params,
    });
  }, //获取表格的主要接口

  getScrmFollowStatistics: function(params, data) {
    return axios.post('/api/SCRM/GetScrmFollowStatistics', data, {
      params: params,
    }); //这里应该跟着状态的，但现在还不是
  },

  getScrmCompanyStatistics: function(params, data) {
    return axios.post('/api/SCRM/GetScrmCompanyStatistics', data, {
      params: params,
    }); //这里应该跟着状态的，但现在还不是
  }, //外部联系人 数据统计(24h)

  SCRMCustomerChange: function(params, data) {
    // let url = '/api/SCRM/SCRMCustomerChange';
    let url = '/api/SCRM/SCRMCustomerChangeV2';
    return axios.post(url, data, {
      params: params,
      timeout: 1000 * 60,
    });
  }, //外部联系人数据改派

  updateRemark: function(params, data) {
    return axios.post('/api/SCRM/UpdateRemark', data, {
      params: params,
    });
  }, //修改备注
  getTagList: function(params, data) {
    return axios.post(`/api/SCRM/GetTagList`, data, {
      params: params,
    });
  }, //获取外部联系人标签信息

  // 获取报表列表
  getRFReportForms: function(params) {
    // http://test.zfxfu.com:60967/api/ReportForms/GetRFReportForms?companyEmployeeId=837
    return axios.get(`/api/ReportForms/GetRFReportForms`, {
      // companyEmployeeId
      params: params,
      baseURL: `${CONFIG.hostIM}`,
    });
  }, //留痕报备sys，文档参考http://test.zfxfu.com:9997/

  savePNResourcesTrading: function(params, data) {
    // let url = '/api/PNResources/SavePNResourcesTrading';//旧，可能废弃
    let url = '/api/PNResources/SavePNResourcesTradingExternalContacts'; //现用
    return axios.post(url, data, { params: params });
  }, // 提交成交信息,data:// companyEmployeeId

  获取外部联系人信息成交信息: function(params, data) {
    let url = '/api/PNResources/GetPNResourcesTradingExternalContacts';
    return axios.post(url, data, { params: params });
  }, //获取外部联系人信息成交信息

  保存成交信息: function(params, data) {
    return axios.post(url, data, { params: params });
  }, //保存成交信息(外部联系人)

  addSCRMPhoneNumber: function(params, data) {
    return axios.post(`/api/SCRM/AddSCRMPhoneNumber`, data, {
      params: params,
    });
  },
  delSCRMPhoneNumber: function(params, data) {
    return axios.post(`/api/SCRM/DeleteSCRMPhoneNumber`, data, {
      params: params,
    });
  },
  callSCRMPhoneNumber: function(params, data) {
    return axios.post(`/api/SCRM/CallSCRMPhoneNumber`, data, {
      params: params,
    });
  }, // 呼叫SCRM电话号码

  addUserTags: function(params, data) {
    return axios.post(`/api/SCRM/AddTagInfo`, data, {
      params: params,
    });
  }, // 添加用户标签
  delUserTags: function(params, data) {
    return axios.post(`/api/SCRM/DeleteTagInfo`, data, {
      params: params,
    });
  }, // 删除用户标签
  getUserTags: function(params, data) {
    return axios.post(`/api/SCRM/getTagInfo`, data, {
      params: params,
    });
  }, // 获取用户标签

  getPhoneNumberCallLog: function(params, data) {
    return axios.post(`/api/SCRM/GetPhoneNumberCallLog`, data, {
      params: params,
    });
  }, // 录音下发

  updata某客户描述: function(params, data) {
    return axios.post(`/api/SCRM/UpdateScrmDescription`, data, {
      params: params,
    });
  },

  updata访问状态: function(params, data) {
    let url = '/api/SCRM/UpdateIsAccessToRoom';
    return axios.post(url, data, { params: params });
  }, //更新 是否禁止进入直播间？
  备注列表: {
    getList: function(params, data) {
      let url = this.path + '/GetScrmRemark';
      return axios.post(url, data, { params: params });
    },

    add: function(params, data) {
      let url = this.path + '/AddScrmRemark';
      return axios.post(url, data, { params: params });
    },
    remove: function(params, data) {
      let url = this.path + '/DeleteScrmRemark';
      return axios.post(url, data, { params: params });
    },
    updata: function(params, data) {
      let url = this.path + '/EditScrmRemark';
      return axios.post(url, data, { params: params });
    },
    path: '/api/SCRM',
  },
  录音列表: {
    get: function(params, data) {
      // Object.assign(data, {
      // phoneNumber: "13173618798"
      //   phoneNumber1: "18650742120",
      //   phoneNumber2: "18608337131"
      // });
      let url = this.path + '/GetPhoneNumberCallLog';
      return axios.post(url, data, { params: params });
    },
    getByWx: function(params, data) {
      // 按约定只需要以下参数：
      // "company_Department_Company_Id": 0,
      // "company_Employee_Id": 0,
      // "external_userid": "string",
      // "eS_Company_Id": "string",
      // Object.assign(data, {
      //   external_userid: "wmbRRaDAAAeJaja4BoIuS1URL130atHQ",
      //   eS_Company_Id: "wwcda5b9b82135b5a7"
      // });
      let url = this.path + '/GetWxPhoneNumberCallInfo';

      return axios.post(url, data, { params: params });
    },
    path: '/api/SCRM',
  },

  工作台资源绑定: {
    获取所有表单信息: function(params, data) {
      let url = '/api/SCRM/GetPnResourcesInfo';
      return axios.post(url, data, { params: params });
    }, // 表单资源数据下发
    setBinding: function(params, data) {
      let url = '/api/SCRM/SCRMLinkPnResourcesBind';
      return axios.post(url, data, { params: params });
    }, // SCRM资源与表单资源绑定
  },

  会话存档同步: {
    获取所有会话: function(params, data) {
      let url = this.path + '/ams/api/message/records';
      let now = moment().unix();
      let key = MD5(this.key + now).toLowerCase();
      data = {
        params: Object.assign(
          data,
          {
            nowTime: now,
            sign: key,
          },
          {
            // "wxId": "ww99599aeb65805948",
            // "sendId": "wmBGLvEAAAMJoIlg3203VXaTFbE-iqaQ",
            // "receiveId": "wmBGLvEAAAMJoIlg3203VXaTFbE-iqaQ",
            // "startTime": 1611651603000,
          },
        ),
      };
      return axios.post(url, data, { params: params });
    }, // 表单资源数据下发
    key: 'f097f902d77743fcb27d74e6cdb9f8f6',
    path: `${CONFIG.hostRF}`,
    /*
      该接口来自杭州给的docs，转述如下
      参数:{
        wxId:	String	是	企业微信id
        sendId:	String	否	发送用户id
        receiveId:	String	否	接收用户id
        startTime:	Long	否	开始时间 ms单位（13位的时间戳）
        endTime:	Long	否	结束时间 ms单位（13位的时间戳）
        nowTime:	Long	是	当前时间10位的时间戳，以秒为单位，验证消息的时效性：当前时间的前后10分钟有效
        sign:	String	是	加密后的MD5值,（key值 + nowTime）MD5
        from:	Integer	是	分页参数，起始位置
        size:	String	是	分页参数，获取条数
      }
      1.4.1.1 返回成功消息json格式
      {
        "version": "1.0",
        "requestId": null,
        "code": 8200,
        "msg": null,String	调用返回的消息
        "errcode": null,
        "errmsg": null,
        "result": {Integer	表示查询结果状态：8200表示调用成功,其他均为失败Object	返回的数据
          "message": [Object	返回的消息对象数组
            {
              "id": 10977,
              "msgid": "7518882268962319834_1612082721_external",String	消息id，消息的唯一标识，
              "action": "send",String	消息动作，目前有send(发送消息)/recall(撤回消息)/switch(切换企业日志)三种类
              "sfrom": "BaiCha",String	消息发送方id。同一企业内容为userid，非相同企业为openid
              "tolist": "wmp78jBwAAF1vBcQcoYteYb7tHkzoKLQ",String	消息接收方列表，可能是多个，同一个企业内容为userid，非相同企业为openid
              "roomid": null,String	群聊消息的群id。如果是单聊则为空
              "msgtime": 1612758721897,	Long	消息发送时间戳，utc时间，ms单位
              "msgtype": "text",String	消息类型,文本消息为：text
              "content": "可以啊",String	消息内容
              "sdkfileid": null,String	媒体资源的id信息。String类型
              "md5sum": null,String	资源的md5值，供进行校验。String类型
              "filesize": null,Integer	资源的文件大小。Uint32类型
              "voiceSize": null,Long	语音消息大小
              "playLength": null,Long	播放长度
              "mediaUrl": null,String	媒体url
              "corpId": "ww148b267da66793a8",String	企业微信corpId
              "sendTime": "2021-01-31 16:45:21" LocalDateTime  发送时间
            }
          ],
          "total": 102	Integer	符合筛选条件的总消息数
        }
      }
    */
  },

  报表: {
    getList报表ByUserInfo: function(params) {
      let url = '/api/ScrmReport/GetScrmReportList';
      // return Promise.resolve(
      //   Mock.mock({
      //     code:200,
      //     message:'',
      //     'data|8':[{
      //       'report_Id|+1':0,
      //       company_Employee_Id:'wx@id',
      //       eS_Company_Id:'@id',
      //       external_userid:'@id',
      //       title:'@cword',
      //       'checkState|0-3':0,
      //       isComplete:'@boolean',
      //       addTime:'@datetime("yy-MM-dd HH:mm:ss")',
      //       editTime:'@datetime("yy-MM-dd HH:mm:ss")',
      //     }]
      //   })
      // )
      return axios.get(url, { params: params });
    }, //获取报表列表
    获取报表Info: function(params) {
      let url = '/api/ScrmReport/GetScrmReport';
      // return Promise.resolve({
      //   code:200,
      //   data:{
      //     "report_Id": 0,
      //     "company_Employee_Id": 0,
      //     "eS_Company_Id": "string",
      //     "external_userid": "string",
      //     "title": "string",
      //     "checkState": 0,
      //     "isComplete": true,
      //     "addTime": "2023-09-01T02:03:43.724Z",
      //     "editTime": "2023-09-01T02:03:43.724Z"
      //   },
      // })
      return axios.get(url, { params: params });
    }, //获取报表
    获取报表List: function(params) {
      let url = '/api/ScrmReport/GetScrmReportRList';
      // return Promise.resolve(Mock.mock({
      //   code:200,
      //   message:'',
      //   data:[
      //     "10905","10906","10907","10908","10909","10910",
      //     "10911","10912","10913","10914","10915","10916",
      //     "10917","10918","10919","10920","10921","10922","10923",
      //   ].map(v=>{
      //     return {
      //       id:0,
      //       report_Id:0,
      //       msgid:v,
      //       addTime:'',
      //     }
      //   })
      // }))
      return axios.get(url, { params: params });
    }, //获取报表详细
    创建报表返Id: function(params, data) {
      let url = '/api/ScrmReport/ScrmReportAdd';
      return axios.post(url, data, { params: params });
    }, //添加报表
    update报表ById: function(params, data) {
      let url = '/api/ScrmReport/ScrmReportUpdate';
      return axios.post(url, data, { params: params });
    }, //更新报表信息
    del报表ById: function(params) {
      let url = '/api/ScrmReport/ScrmReportDel';
      return axios.get(url, { params: params });
    }, //删除报表
    逐条添加: function(params) {
      let url = '/api/ScrmReport/ScrmReportRAdd';
      return axios.get(url, { params: params });
    }, //添加报表明细
    逐条删除: function(params) {
      let url = '/api/ScrmReport/ScrmReportRDel';
      return axios.get(url, { params: params });
    }, //删除报表消息
    成交报表信息下发: function(params, data) {
      let url = '/api/SCRM/GetScrmReport';
      return axios.post(url, data, { params: params });
    },
    getList报表数据ByMsgId: function(params, data) {
      let url = this.path + '/ams/api/message/list';
      // let url = 'https://demo-m-api.topxlc.com/'+'ams/api/message/list';
      let now = moment().unix();
      let key = MD5(this.key + now).toLowerCase();
      data = {
        params: Object.assign(
          data,
          {
            sort: 1,
            nowTime: now,
            sign: key,
          },
          {
            // wxId: "ww99599aeb65805948",
            // "sendId": "wmBGLvEAAAMJoIlg3203VXaTFbE-iqaQ",
            // "receiveId": "wmBGLvEAAAMJoIlg3203VXaTFbE-iqaQ",
            // "startTime": 1611651603000,
            // msgIdsList:[
            //   '733025205872379756_1612079199_external',
            //   '5169474803441925574_1612079256_external',
            //   '1503724226605089941_1612079262_external',
            //   '9022336461375223701_1612079283_external',
            //   '4580015527170396451_1612079290_external',
            //   '15282992132577535357_1612079290_external',
            //   '11780194901198906752_1612079405_external',
            //   '2881449247187675376_1612079441_external',
            //   '17300727911308824259_1612079456_external',
            //   '14441728780875507629_1612079456_external',
            //   '146193796225736285_1612079456_external',
            //   '14638783230787460643_1612079456_external',
            //   '1289574002229656061_1612079456_external',
            //   '6729342107936250234_1612079456_external',
            //   '8555956190531159317_1612079456_external',
            //   '12127294957936765035_1612079456_external',
            //   '12147619422734572611_1612079456_external',
            //   '437980657833672196_1612079456_external',
            //   '8487378857048658520_1612079456_external',
            //   '5657247923030012856_1612079456_external',
            //   '14557023419414801176_1612079456_external',
            //   '15122823397211132820_1612079456_external',
            //   '6859101556124251688_1612079456_external',
            // ]
          },
        ),
      };
      return axios.post(url, data, { params: params });
    },
    key: 'f097f902d77743fcb27d74e6cdb9f8f6',
    path: `${CONFIG.hostRF}`,
  },
  直播间: {
    直播间账号列表下发: function(params, data) {
      let url = '/api/SCRM/GetCompanyEmployeeZhiBoAccount';
      return axios.post(url, data, { params: params });
    },
  },

  查看开发资源排查数据: function(params) {
    let url = '/api/SCRM/GetPNResourcesBlackList';
    let verifykey = MD5(moment().format('YYYYMMDD')).toUpperCase();
    return axios.get(url, {
      params: Object.assign(params, { verifykey: verifykey }),
    });
  },
};

export { axios, api };
